package cn.chint.controller;

import cn.chint.model.SysUser;
import cn.chint.model.User;
import cn.chint.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//import org.apache.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.client.RestTemplate;

@Controller
@CrossOrigin
public class AdminController {

	@Autowired
	UserService userService;

	@Autowired
	RestTemplate restTemplate;
	//public Logger log = Logger.getLogger(getClass());
	private static final Logger logger = LogManager.getLogger(AdminController.class);

//    @CrossOrigin
//    @RequestMapping(value = "userLogin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ResponseBody
//    public String userLogin(@RequestParam(value="s_form_data",required = true) String s_form_data,HttpServletRequest req, HttpServletResponse resp) throws IOException {
//		logger.info(s_form_data);
//    	JSONObject jsonObj = new JSONObject();
//    	try{
//	    	JSONObject jb  = JSONObject.parseObject(s_form_data);
//	    	String username=jb.getString("username");
//	    	String password=jb.getString("password");
//
//	    	SysUser sysUser = userService.selectSysUser(username,password);
//	    	if(sysUser==null){
//	            jsonObj.put("status", false);
//	    		jsonObj.put("msg", "登录失败，账户或密码错误。");
//	    	}else {
//				HttpSession session = req.getSession();
////				// 2.将用户名保存在session中
////				session.setAttribute("sysUser", sysUser);
//			}
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
//    	return jsonObj.toString();
//
//    }

	/**登录*/
	@CrossOrigin
	@RequestMapping(value = "userLogin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String userLogin(@RequestParam(value="s_form_data",required = true) String s_form_data,HttpServletRequest req, HttpServletResponse resp) throws IOException {
		JSONObject jsonObj = new JSONObject();
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			//headers.set("","");
			logger.info(s_form_data);

			JSONObject jb  = JSONObject.parseObject(s_form_data);
	    	String username=jb.getString("username");
	    	String password=jb.getString("password");
			Map<String,Object> map = new HashMap<>();
			map.put("username",username);
			map.put("password",password);
			HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(map),headers);

			String uri ="https://cc-common.chintcloud.net/common-api/api/v1.0/user-center/login";
			//Map  m = restTemplate.exchange(uri, HttpMethod.POST,entity,Map.class).getBody();
			Map m = restTemplate.exchange(uri, HttpMethod.POST, entity, Map.class).getBody();
			logger.info(JSON.toJSONString(m));
			String code=m.get("code").toString();
			String msg=m.get("msg").toString();
			Map mapdata=(Map) m.get("data");

			if("200".equals(code)){
				String token=mapdata.get("token").toString();
				logger.info(token);
				HttpSession session = req.getSession();
//				// 2.将用户名保存在session中
				session.setAttribute("token", token);
				session.setAttribute("username", username);
			}else {
				jsonObj.put("status", false);
	    		jsonObj.put("msg", "登录失败，账户或密码错误。");
			}


		}catch (Exception e){
			e.printStackTrace();
		}
		return  jsonObj.toString();
	}



	@GetMapping("home")
	public String home(HttpServletRequest request, HttpServletResponse response) throws IOException {

		logger.info("跳转登录页");
		logger.debug("debug");
		logger.error("error");
		logger.warn("warn");
		//response.sendRedirect("/pages/layui/index.html");
		return "layui/login";
	}

	/**
	 * 跳转到首页
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/direct_home")
	public String direct_home(HttpServletRequest request,HttpServletResponse response) throws IOException{

		logger.info("跳转首页");
		//response.sendRedirect(request.getContextPath() + "/pages/layui/index.html");
		return "layui/index";
	}
	/**
	 * 跳转到回路页
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/huilu")
	public String huilu(HttpServletRequest request,HttpServletResponse response) throws IOException{

		//response.sendRedirect(request.getContextPath() + "/pages/layui/index.html");
		return "layui/huilu";
	}

	/**
	 * 跳转到shouye页
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/shouye")
	public String shouye(HttpServletRequest request,HttpServletResponse response) throws IOException{

		//response.sendRedirect(request.getContextPath() + "/pages/layui/index.html");
		return "layui/shouye";
	}
	/**
	 * 跳转到yici页
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/yici")
	public String yici(HttpServletRequest request,HttpServletResponse response) throws IOException{
		//response.sendRedirect(request.getContextPath() + "/pages/layui/index.html");
		return "layui/yici";
	}
	/**
	 * 跳转到fenxi页
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/fenxi")
	public String fenxi(HttpServletRequest request,HttpServletResponse response) throws IOException{

		//response.sendRedirect(request.getContextPath() + "/pages/layui/index.html");
		return "layui/fenxi";
	}
	/**
	 * 跳转到huilucanshu页
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/huilucanshu")
	public String huilucanshu(HttpServletRequest request,HttpServletResponse response) throws IOException{

		//response.sendRedirect(request.getContextPath() + "/pages/layui/index.html");
		return "layui/huilucanshu";
	}

    /**
	 * 首页获取用户和菜单
	 * @return
	 * @throws IOException
	 */

    @RequestMapping(value = "get_channel_user",  produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String get_channel_user(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException {

    	SysUser user = (SysUser)request.getSession().getAttribute("sysUser");
    	JSONObject jsonObj = new JSONObject();
    	//int level=user.getLevel();
		int level=1;

    	String menu;
    	if (level==0) {
    		menu =
	    	    	"<li class=\"layui-nav-item layui-this\">"+
	    	         "  <a href=\"javascript:;\" data-url=\"\" data-id=\"1\">项目列表</a>"+
	    	        "</li>" +
	    	        "<li class=\"layui-nav-item layui-this\">"+
   	    	         "  <a href=\"javascript:;\" data-url=\"\" data-id=\"2\">项目接收人</a>"+
   	    	        "</li>" +
	    	        "<li class=\"layui-nav-item layui-this\">"+
  	    	         "  <a href=\"javascript:;\" data-url=\"\" data-id=\"3\">关注用户列表</a>"+
  	    	        "</li>";
		} else {
			menu ="<li class=\"layui-nav-item layui-this\">"+
                    "<a href=\"javascript:;\" data-url=\"shouye\" data-id=\"1\">首页</a>"+
                    "</li>" +
					"<li class=\"layui-nav-item layui-this\">"+
							"<a href=\"javascript:;\" data-url=\"#\" data-id=\"2\">上海自动化软件有限公司</a>"+
							"<dl class=\"layui-nav-child\">"+
							"  <dd><a href=\"javascript:;\" data-url=\"yici\" data-id=\"2_1\">A区一号配电房</a></dd>" +
                            "  <dd style='margin-left:20px;'><a href=\"javascript:;\" data-url=\"huilu\" data-id=\"2_11\">A区一号配电房1号系统</a></dd>" +
							"	<p style='margin-left:75px;font-size:12px'>D1_1进线柜</p>" +
							"	<p style='margin-left:75px;font-size:12px'>D2_电容主柜</p>" +
							"	<p style='margin-left:75px;font-size:12px'>D3_电容副柜</p>" +
							"	<p style='margin-left:75px;font-size:12px'>D4_馈线柜</p>" +
							"   <dd style='margin-left:45px;'><a href=\"javascript:;\" data-url=\"huilucanshu\" data-id=\"2_1141\">研发楼消防回路</a></dd>" +
							"   <dd style='margin-left:45px;'><a href=\"javascript:;\" data-url=\"huilucanshu\" data-id=\"2_1142\">研发楼照明回路</a></dd>" +
							"   <dd style='margin-left:45px;'><a href=\"javascript:;\" data-url=\"huilucanshu\" data-id=\"2_1143\">研发楼空调回路</a></dd>" +
							"</dl>"+
					"</li>"
//                    +
//	    	    	"<li class=\"layui-nav-item layui-this\">"+
//	    	            "<a href=\"javascript:;\" data-url=\"yici\" data-id=\"2\">运行状态</a>"+
//						"<dl class=\"layui-nav-child\">"+
//						"	<dd><a href=\"javascript:;\" data-url=\"yici\" data-id=\"2_1\">一次系统运行图</a></dd>" +
//						"</dl>"+
//	    	        "</li>" +
//	    	        "<li class=\"layui-nav-item layui-this\">"+
//						"<a href=\"javascript:;\" data-url=\"https://www.baidu.com\" data-id=\"3\">运行数据</a>"+
//						"<dl class=\"layui-nav-child\">"+
//						"	<dd><a href=\"javascript:;\" data-url=\"huilu\" data-id=\"3_1\">回路运行画面</a></dd>" +
//						"	<dd><a href=\"javascript:;\" data-url=\"huilucanshu\" data-id=\"3_2\">运行参数趋势</a></dd>" +
//						" </dl>"+
//   	    	        "</li>" +
//	    	        "<li class=\"layui-nav-item layui-this\">"+
// 	    	            "<a href=\"javascript:;\" data-url=\"loophot\" data-id=\"4\">能效管理</a>"+
//						"<dl class=\"layui-nav-child\">"+
//						"	<dd><a href=\"javascript:;\" data-url=\"huilucanshu\" data-id=\"4_1\">回路能效统计</a></dd>" +
//						" </dl>"+
// 	    	        "</li>"
//							+
//	    	        "<li class=\"layui-nav-item layui-this\">"+
//	    	         "  <a href=\"javascript:;\" data-url=\"https://www.baidu.com\" data-id=\"5\">运行维护</a>"+
//	    	        "</li>"+
//					"<li class=\"layui-nav-item layui-this\">"+
//					"  <a href=\"javascript:;\" data-url=\"https://www.baidu.com\" data-id=\"6\">用户管理</a>"+
//					"</li>"
					;
		}
		HttpSession session = request.getSession();
//				// 2.将用户名保存在session中
		session.getAttribute("username");
		jsonObj.put("menu", menu);
		jsonObj.put("channel_user_name",session.getAttribute("username"));
	//	jsonObj.put("channel_user_id", user.getId());
    	return jsonObj.toString();

    }

    @RequestMapping(value = "exit_login",  produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String exit_login(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException {

    	request.getSession().invalidate();

    	response.sendRedirect(request.getContextPath() + "/home");


    	return null;

    }



}





